package com.jiangchao.mimidao.framework.util;

import com.jiangchao.mimidao.framework.annotation.Param;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ParameterNameUtils {

  private ParameterNameUtils() {
  }

  /**
   * 获得方法所有@Param注解的值
   */
  public static Map<String, Object> getMethodParameterNamesByAnnotation(Method method,
      Object[] args) {
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    if (parameterAnnotations == null || parameterAnnotations.length == 0) {
      return null;
    }
    Map<String,Object> map = new HashMap<String, Object>();
    for (int i = 0; i < parameterAnnotations.length; i++) {
      for (int j = 0; j < parameterAnnotations[i].length; j++) {
        Annotation annotation = parameterAnnotations[i][j];
        if (annotation instanceof Param){
          map.put(((Param) annotation).value(),args[i]);
        }
      }
    }
    return map;
  }

  public void method1(@Param("parameter1") String param1, @Param("parameter2") String param2,
      String param3) {
  }

  public static void main(String[] args) throws Exception {
    Method method = null;
    method = ParameterNameUtils.class
        .getMethod("method1", String.class, String.class, String.class);
    Map<String,Object> map = getMethodParameterNamesByAnnotation(method, new String[]{"p1", "p2", "p3"});
    for (String key:map.keySet()){
      System.out.println("key="+key+",value="+map.get(key));
    }
  }


}
